package com.ray.system.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.builder.PositionBuilder;
import com.ray.system.check.PositionCheck;
import com.ray.system.enums.DataAuthEnum;
import com.ray.system.service.SysPositionService;
import com.ray.system.table.dto.PositionQueryDTO;
import com.ray.system.table.entity.SysPosition;
import com.ray.system.table.params.position.PositionCreateParams;
import com.ray.system.table.params.position.PositionEditParams;
import com.ray.system.table.params.position.PositionQueryParams;
import com.ray.system.table.vo.position.PositionVO;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.enums.YesOrNoEnum;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 职位相关服务
 * @Class: PositionApi
 * @Package com.ray.system.api
 * @date 2020/5/27 11:15
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class PositionApi {

    @Autowired
    private SysPositionService sysPositionService;


    /**
     * 查询职位列表信息 分页  非删除的
     * @param queryParams
     * @return
     */
    public Result<IPage<PositionVO>> pagePositions(CommonPage<PositionQueryParams,Page<PositionVO>> queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        CommonPageBuilder<PositionQueryDTO,SysPosition> commonPageBuilder = new CommonPageBuilder<>(PositionQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());
        IPage<SysPosition> page = sysPositionService.page(commonPageBuilder.bulid(),loginUser);
        List<SysPosition> positions = page.getRecords();
        //结果对象
        IPage<PositionVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if(ObjectUtil.isNotNull(positions)){
            pageList.setRecords(positions.stream().map(sysPosition -> {
                PositionVO positionVO = new PositionVO();
                BeanUtil.copyProperties(sysPosition,positionVO);
                return  positionVO;
            }).collect(Collectors.toList()));
        }else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,pageList);
    }

    /**
     * 查询职位列表信息--启用的职位
     * @param queryParams
     * @return
     */
    public Result<List<PositionVO>> queryPositions(PositionQueryParams queryParams){
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        PositionQueryDTO queryDTO = new PositionQueryDTO();
        BeanUtil.copyProperties(queryParams,queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        List<SysPosition> positions = sysPositionService.list(queryDTO,loginUser);
        //查询对象
        List<PositionVO> list = new ArrayList<>();
        if(ObjectUtil.isNotNull(positions)){
            list = positions.stream().map(sysPosition -> {
                PositionVO positionVO = new PositionVO();
                BeanUtil.copyProperties(sysPosition,positionVO);
                return  positionVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,list);
    }

    /**
     * 查询可用
     * @param queryParams
     * @return
     */
    public Result<List<PositionVO>> queryUsablePositions(@Valid PositionQueryParams queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        PositionQueryDTO queryDTO = new PositionQueryDTO();
        BeanUtil.copyProperties(queryParams,queryDTO);
        queryDTO.setStatus(YesOrNoEnum.YES.getValue());
        if(!loginUser.isAllData()){
            queryDTO.setUseble(YesOrNoEnum.YES.getValue());
        }
        List<SysPosition> positions = sysPositionService.usable(queryDTO);
        //查询对象
        List<PositionVO> list = new ArrayList<>();
        if(ObjectUtil.isNotNull(positions)){
            list = positions.stream().map(sysPosition -> {
                PositionVO positionVO = new PositionVO();
                BeanUtil.copyProperties(sysPosition,positionVO);
                return  positionVO;
            }).collect(Collectors.toList());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,list);
    }



    /**
     * 创建职位
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createPosition(PositionCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        DataAuthEnum dataAuth = DataAuthEnum.getEnum(createParams.getDataAuth());
        new AbstractCheck<>(dataAuth).checkNull(SysMsgCodeConstant.Error.ERR10000001);
        PositionBuilder positionBuilder = new PositionBuilder();
        positionBuilder.append(createParams).appendStatus(YesOrNoEnum.YES.getValue()).appendCreate(loginUser);
        //保存职位信息
        if(!sysPositionService.save(positionBuilder.bulid())){
            log.info("保存职位接口异常,参数:{}", JSON.toJSONString(positionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
       return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,positionBuilder.getCode());
    }

    /**
     * 编辑职位
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editPosition(PositionEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        DataAuthEnum dataAuth = DataAuthEnum.getEnum(editParams.getDataAuth());
        new AbstractCheck<>(dataAuth).checkNull(SysMsgCodeConstant.Error.ERR10000001);
        PositionBuilder positionBuilder = new PositionBuilder();
        positionBuilder.append(editParams).appendEdit(loginUser);
        //编辑职位信息
        if(!sysPositionService.edit(positionBuilder.bulid(),loginUser)){
            log.info("编辑职位接口异常,参数:{}", JSON.toJSONString(positionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,positionBuilder.getCode());
    }


    /**
     * 删除职位
     * @param positionCode 职位编码
     * @return Result
     */
    @Transactional
    public Result<String> deletePosition(String positionCode) {
        ValidateUtil.hasLength(positionCode,"参数[positionCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysPosition sysPosition = sysPositionService.queryPositionByPositionCode(positionCode,loginUser);
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        PositionBuilder positionBuilder = new PositionBuilder();
        positionBuilder.appendCode(positionCode).appendEdit(loginUser).delete();
        //删除职位信息
        if(!sysPositionService.edit(positionBuilder.bulid(),loginUser)){
            log.info("删除职位接口异常,参数:{}", JSON.toJSONString(positionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,positionBuilder.getCode());
    }

    /**
     * 开启职位
     * @param positionCode 职位编码
     * @return Result
     */
    @Transactional
    public Result<String> openPosition(String positionCode) {
        ValidateUtil.hasLength(positionCode,"参数[positionCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysPosition sysPosition = sysPositionService.queryPositionByPositionCode(positionCode,loginUser);
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        PositionBuilder positionBuilder = new PositionBuilder();
        positionBuilder.appendCode(positionCode).appendEdit(loginUser).open();
        //开启职位信息
        if(!sysPositionService.edit(positionBuilder.bulid(),loginUser)){
            log.info("开启职位接口异常,参数:{}", JSON.toJSONString(positionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,positionBuilder.getCode());
    }

    /**
     * 开启职位
     * @param positionCode 职位编码
     * @return Result
     */
    @Transactional
    public Result<String> closePosition(String positionCode) {
        ValidateUtil.hasLength(positionCode,"参数[positionCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysPosition sysPosition = sysPositionService.queryPositionByPositionCode(positionCode,loginUser);
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        PositionBuilder positionBuilder = new PositionBuilder();
        positionBuilder.appendCode(positionCode).appendEdit(loginUser).close();
        //关闭职位信息
        if(!sysPositionService.edit(positionBuilder.bulid(),loginUser)){
            log.info("关闭职位接口异常,参数:{}", JSON.toJSONString(positionBuilder.bulid()));
            throw BusinessExceptionFactory.newException(MsgCodeConstant.Error.ERR00000001);
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001,positionBuilder.getCode());
    }

    /**
     * 职位详情
     * @param positionCode 职位编码
     * @return Result
     */
    public Result<PositionVO> viewPosition(String positionCode) {
        ValidateUtil.hasLength(positionCode,"参数[positionCode]不能为空");
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //获取权限信息
        SysPosition sysPosition = sysPositionService.queryPositionByPositionCode(positionCode,loginUser);
        new PositionCheck(sysPosition).checkNull(SysMsgCodeConstant.Error.ERR10000002);
        PositionVO positionVO = new PositionVO();
        BeanUtil.copyProperties(sysPosition,positionVO);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002,positionVO);
    }

}
